using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace Yoozoo.Gameplay.City
{
    [Serializable]
    public class CityBuildingsData
    {
        public List<CityBuildingData> buildings;
    }
    [Serializable]
    public class CityBuildingData
    {
        public List<CityBuildingFloorCellData> cells;
        public int buildingId;
    }
    public class CityBuildingsFloorEditor : MonoBehaviour
    {
#if UNITY_EDITOR
        [Header("导出的建筑地板配置路径")]
        public string outPutBuildingFloorConfigPath;
       public void Begin()
       {
              //获取所有建筑
              var buildings = transform.GetComponentsInChildren<CityBuildingFloorEditor>();
              CityBuildingsData cityBuildingsData = new CityBuildingsData();
              cityBuildingsData.buildings = new List<CityBuildingData>();
              Debug.Log("当前建筑数量："+buildings.Length);
              //遍历所有建筑
              foreach (var building in buildings)
              {
                //获取建筑的地板数据
                var buildingFloorData = building.GetBuildingFloorData();
                CityBuildingData cityBuildingData = new CityBuildingData();
                cityBuildingData.cells = buildingFloorData;
                cityBuildingData.buildingId = building.id;
                cityBuildingsData.buildings.Add(cityBuildingData);
              }
              //导出建筑的地板数据
              ExportBuildingFloorData(cityBuildingsData);
       }
       
       private void ExportBuildingFloorData(CityBuildingsData buildingsFloorData)
       {
           //导出建筑的地板数据
           var json = JsonUtility.ToJson(buildingsFloorData);
           //写入文件
           // FileStream fs = new FileStream(Application.dataPath + outPutBuildingFloorConfigPath, FileMode.Create, FileAccess.Write);
           // using (StreamWriter writer = new StreamWriter(fs))
           // {
           //     writer.Write(json);
           //     writer.Flush();
           //     writer.Close();
           //     fs.Close();
           // }
           var luaText = JsonToLua.ConvertLua(json);
           var floorLuaPath = $"{Application.dataPath}/../Lua/modules/city/config/cityBuildingsFloorConfig.lua";
           FileStream luafs = new FileStream(floorLuaPath, FileMode.Create, FileAccess.Write);
           using (StreamWriter writer = new StreamWriter(luafs))
           {
               writer.Write(luaText);
               writer.Flush();
               writer.Close();
               luafs.Close();
           }
           Debug.Log("导出结束！");
           AssetDatabase.Refresh();
       }
#endif
        
    }
}
